<template>
  <div class="selfTest_container" @contextmenu.prevent @dblclick.prevent>
    <div class="left" ref="leftRef" @contextmenu.prevent="handleRightClick">
      <div class="squares-container">
        <div
          v-for="i in total"
          :key="i"
          class="square_item"
          @mousedown.left="handleLeftClick(i - 1)"
          :class="{
            marked: tapIndex.includes(i - 1),
            answered: isAnswered(i - 1),
            active: index === i - 1,
          }"
        >
          {{ i }}
        </div>
      </div>
    </div>
    <div class="center" ref="centerRef">
      <div class="context_item">
        <div :key="item.id" class="head_item">
          {{ index + 1 }}.{{ item.question }}
        </div>
        <!-- 单选框 -->
        <el-radio-group
          class="radio-group"
          v-model="selectedRatio"
          v-show="item.answer.length == 1"
        >
          <el-radio
            class="radio-item"
            :value="'A'"
            @change="radioHandler"
            :label="item.item1"
          />
          <el-radio
            class="radio-item"
            :value="'B'"
            @change="radioHandler"
            :label="item.item2"
          />
          <el-radio
            class="radio-item"
            :value="'C'"
            @change="radioHandler"
            :label="item.item3"
          />
          <el-radio
            class="radio-item"
            :value="'D'"
            v-if="item.item4"
            @change="radioHandler"
            :label="item.item4"
          />
        </el-radio-group>
        <!-- 多选框 -->
        <el-checkbox-group
          class="checkbox-group"
          v-model="selectedChecked"
          v-show="item.answer.length > 1"
        >
          <el-checkbox
            class="checkbox-item"
            :value="'A'"
            @change="checkHandler"
            :label="item.item1"
          />
          <el-checkbox
            class="checkbox-item"
            :value="'B'"
            @change="checkHandler"
            :label="item.item2"
          />
          <el-checkbox
            class="checkbox-item"
            :value="'C'"
            @change="checkHandler"
            :label="item.item3"
          />
          <el-checkbox
            class="checkbox-item"
            v-if="item.item4"
            :value="'D'"
            @change="checkHandler"
            :label="item.item4"
          />
        </el-checkbox-group>
      </div>
      <div class="func_item">
        <!-- 功能区，有提交，收藏，下一题，上一题等各种按钮 -->
        <el-button type="info" icon="ArrowLeft" @click="prev">
          上一题
        </el-button>
        <el-button type="info" icon="ArrowRight" @click="next">
          下一题
        </el-button>
      </div>
    </div>
    <div class="right" ref="rightRef">
      <h4 style="margin-left: 5%">考试科目</h4>
      <span class="subject-text">{{ testSubject }}</span>
      <div
        style="
          height: 1px;
          width: 90%;
          background-color: #dcdfe6;
          margin: 10px auto;
        "
      />
      <div
        style="
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          align-items: center;
          margin-top: 10px;
        "
      >
        <h4>考试时间</h4>
        <span class="time-text">{{
          formatTime(testTime - Math.round((percent * testTime) / 100))
        }}</span>
      </div>
      <div
        style="
          height: 1px;
          width: 90%;
          background-color: #dcdfe6;
          margin: 10px auto;
        "
      />
      <el-button
        style="width: 80%; margin: 20px auto; display: block"
        type="warning"
        size="large"
        icon="Flag"
        @click="tap(null)"
        >标 记</el-button
      >
      <div
        style="
          height: 1px;
          width: 90%;
          background-color: #dcdfe6;
          margin: 10px auto;
        "
      />
      <el-button
        type="primary"
        style="width: 80%; margin: 20px auto; display: block"
        icon="Check"
        size="large"
        @click="submitExam(true)"
      >
        交 卷
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { useStore } from "vuex";
import selfTestApi from "@/api/selfTest/index";
import zhiZhaoApi from "@/api/questionItem/questionItem";
import subjectTest from "@/api/subject/test";
import { onBeforeRouteLeave } from "vue-router";

const testSubject = computed(() => {
  if (store.getters.selectValue) {
    const index = store.getters.selectValue.indexOf("/");
    if (index != -1) {
      const arr = store.getters.selectValue.split("/");
      return arr[0] + "\n" + arr[1];
    } else {
      return store.getters.selectValue;
    }
  }
});
const router = useRouter();
const route = useRoute();
const store = useStore();

const leftRef = ref(null);
const centerRef = ref(null);
const rightRef = ref(null);

// 响应式状态

let questionItemId = 0;
const index = ref(0);
const total = ref(0);
const items = ref([]);
const item = ref({
  subject: "",
  question: "",
  item1: "",
  item2: "",
  item3: "",
  item4: "",
  answer: "",
});
const selectedRatio = ref("");
const selectedChecked = ref([]);
const allAnswers = ref([]);
const tapIndex = ref([]);
const percent = ref(0);
const testTime = ref(5);
const setInter = ref(null);
const warningTimer = ref(null);
const isWarningShown = ref(false);
const canRoute = ref(false); //控制是否可以直接跳转出路由

// 当页面隐藏时，自动交卷
// const handleVisiable = (e) => {
//   switch (e.target.visibilityState) {
//     case "hidden":
//       ElMessage.warning("警告！你已经离开当前答题页面，5秒后自动交卷！");
//       setTimeout(() => {
//         submitExam();
//       }, 5000);
//       break;
//   }
// };

const radioHandler = () => {
  for (let i = 0; i < 4; i++) {
    allAnswers.value[index.value][i] = "";
  }
  setAllAnswers(selectedRatio.value);
};

const setAllAnswers = (item) => {
  const idx = index.value;
  switch (item) {
    case "A":
      allAnswers.value[idx][0] = item;
      break;
    case "B":
      allAnswers.value[idx][1] = item;
      break;
    case "C":
      allAnswers.value[idx][2] = item;
      break;
    case "D":
      allAnswers.value[idx][3] = item;
      break;
  }
};

const checkHandler = () => {
  const idx = index.value;
  for (let i = 0; i < 4; i++) {
    allAnswers.value[idx][i] = "";
  }
  selectedChecked.value.forEach((element) => {
    setAllAnswers(element);
  });
};

/**
 * 交卷
 * @param flag 是否自动交卷
 */
const submitExam = (flag) => {
  if (!flag) {
    submitTitle();
  } else {
    if (tapIndex.value.length > 0) {
      ElMessageBox.confirm("还有标记的题目哦，不去看看吗", "确认框", {
        confirmButtonText: "检查一下",
        cancelButtonText: "直接交卷",
        type: "warning",
      })
        .then(() => {
          item.value = items.value[tapIndex.value[0]];
          index.value = tapIndex.value[0];
        })
        .catch(() => {
          submitTitle();
        });
    } else {
      ElMessageBox.confirm("是否确认交卷？", "确认框", {
        confirmButtonText: "直接交卷",
        cancelButtonText: "检查一下",
        type: "warning",
      }).then(() => {
        submitTitle();
      });
    }
  }
};

const tap = (i) => {
  // 如果i在tapIndex中，则删除，否则添加
  if (i) {
    if (tapIndex.value.includes(i)) {
      tapIndex.value = tapIndex.value.filter((e) => e !== i);
    } else {
      tapIndex.value.push(i);
    }
  } else {
    // 处理当前题目的标记/取消标记
    const currentIndex = index.value;
    if (tapIndex.value.includes(currentIndex)) {
      tapIndex.value = tapIndex.value.filter((e) => e !== currentIndex);
    } else {
      tapIndex.value.push(currentIndex);
    }
  }
};

const next = () => {
  if (index.value == total.value - 1) {
    ElMessage({
      message: "已经是最后一题了！",
      type: "error",
    });
    return;
  }
  index.value = index.value + 1;
};

/**
 * 处理键盘导航事件
 * @param {KeyboardEvent} event - 键盘事件
 */
const handleKeyboardNavigation = (event) => {
  // 如果用户正在输入框中输入，不处理键盘导航
  if (event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA") {
    return;
  }

  if (event.key === "ArrowLeft") {
    prev();
  } else if (event.key === "ArrowRight") {
    next();
  }
};

const prev = () => {
  if (index.value == 0) {
    ElMessage({
      message: "已经是第一题了！",
      type: "error",
    });
    return;
  }
  index.value = index.value - 1;
};

const submitTitle = () => {
  // 设置标志，表明正在提交
  canRoute.value = true;

  let rightNum = 0;
  for (let i = 0; i < allAnswers.value.length; i++) {
    let element = allAnswers.value[i].filter((a) => a != "");
    element.sort();
    const selected = element.join("+");
    if (selected == items.value[i].answer) {
      rightNum++;
    }
  }
  const score = Math.round((rightNum / total.value) * 100);
  clearInterval(setInter.value);
  let ids = items.value.map((item) => item.id);
  // 如果路由参数里没有type，则认为是考试，如果有type，则认为是自测
  if (!route.query.type) {
    zhiZhaoApi
      .submit(
        score,
        Math.round((percent.value * testTime.value) / 100),
        questionItemId,
        store.getters.name,
        allAnswers.value,
        ids,
        route.query.title
      )
      .then((res) => {
        ElNotification({ type: "success", message: res.message });
        store.dispatch("learn/setPaperCount", store.getters.paperCount - 1);
        router.push("/test/result");
      });
  } else {
    if (route.query.type === "selfTest") {
      selfTestApi
        .submit(
          score,
          Math.round((percent.value * testTime.value) / 100),
          questionItemId,
          store.getters.name,
          allAnswers.value,
          ids
        )
        .then((res) => {
          ElNotification({ type: "success", message: res.message });
          router.push({
            path: "/learning/review",
            query: { selectedId: store.getters.selectedId },
          });
        });
    } else if (route.query.type === "subjectTest") {
      subjectTest
        .submit(
          score,
          questionItemId,
          Math.round((percent.value * testTime.value) / 100)
        )
        .then((res) => {
          ElNotification({ type: "success", message: res.message });
          router.push({
            path: "/training/index",
          });
        })
        .catch((err) => {
          router.push({
            path: "/training/index",
          });
        });
    }
  }
};

// 监听器
watch(index, (newVal) => {
  selectedRatio.value = "";
  selectedChecked.value = [];
  item.value = items.value[newVal];
  const res = allAnswers.value[newVal].filter((a) => a != "");
  if (items.value[newVal].answer.length > 1) {
    selectedChecked.value = res;
  } else {
    selectedRatio.value = res[0];
  }
});

// 添加处理页面刷新的函数
// const handleBeforeUnload = (event) => {
//   // 对于自测试不自动交卷，仅对其他类型的考试执行
//   if (route.query.type !== "selfTest" && !canRoute.value) {
//     // 显示提示信息（大多数现代浏览器会忽略自定义消息）
//     const message = "刷新页面将自动交卷！";
//     event.preventDefault();
//     event.returnValue = message;

//     // 尝试提交考试（注意：此时页面即将刷新，可能无法完成异步操作）
//     submitExam(false);

//     // 返回自定义消息（虽然大多数浏览器会显示标准消息）
//     return message;
//   }
// };

// 生命周期钩子
onMounted(async () => {
  if (Object.keys(route.query).length == 0) {
    canRoute.value = true;
    router.push("/home");
    return;
  }

  questionItemId = route.query.questionItemId;
  const type = route.query.type;
  window.addEventListener("keydown", handleKeyboardNavigation);
  try {
    // const res = await (type
    //   ? selfTestApi.batchGet(questionItemId)
    //   : zhiZhaoApi.batchGet(questionItemId));

    let res = null;
    if (type) {
      if (type == "selfTest") {
        try {
          res = await selfTestApi.batchGet(questionItemId);
        } catch (error) {
          canRoute.value = true;
          router.push("/learning/index");
          return;
        }
      } else if (type == "subjectTest") {
        try {
          res = await subjectTest.batchGet(questionItemId);
        } catch (error) {
          canRoute.value = true;
          router.push("/training/index");
          return;
        }
      }
    } else {
      try {
        res = await zhiZhaoApi.batchGet(questionItemId);
      } catch (error) {
        canRoute.value = true;
        router.push("/test/index");
        return;
      }
    }

    items.value = res.data.result;
    testTime.value = res.data.time;
    item.value = items.value[0];
    total.value = items.value.length;

    // 初始化答案数组
    allAnswers.value = Array(total.value)
      .fill()
      .map(() => Array(4).fill(""));

    // 启动计时器
    let t1 = 1;
    setInter.value = setInterval(() => {
      t1++;
      percent.value = (t1 / testTime.value) * 100;
      if (Math.round(percent.value) == 100) {
        submitExam(false);
      }
    }, 1000);

    // 添加页面刷新事件监听
    // window.addEventListener("beforeunload", handleBeforeUnload);

    // 初始计算文本高度
  } catch (error) {
    console.error("Error fetching questions:", error);
    ElMessage.error("获取题目失败");
    if (!type) {
      canRoute.value = true;
      router.push("/home");
    }
  }
  // if (route.path == "/test/startTest") {
  // } else {
  // }

  // 除了自我测试，都会监控页面，如果离开页面，3秒后自动交卷
  // if (route.query.type != "selfTest") {
  //   document.addEventListener("visibilitychange", handleVisibilityChange);
  // }
});

onBeforeUnmount(() => {
  window.removeEventListener("keydown", handleKeyboardNavigation);
  if (route.query.type != "selfTest") {
    clearInterval(setInter.value);
    if (warningTimer.value) {
      clearInterval(warningTimer.value);
    }
    // document.removeEventListener("visibilitychange", handleVisibilityChange);
  }

  // 移除页面刷新事件监听
  // window.removeEventListener("beforeunload", handleBeforeUnload);
});

// 添加右键点击处理函数
const handleRightClick = (event) => {
  // 获取点击的题目索引
  const squareElements = document.querySelectorAll(".square_item");
  const clickX = event.clientX;
  const clickY = event.clientY;

  for (let i = 0; i < squareElements.length; i++) {
    const rect = squareElements[i].getBoundingClientRect();
    if (
      clickX >= rect.left &&
      clickX <= rect.right &&
      clickY >= rect.top &&
      clickY <= rect.bottom
    ) {
      // 设置当前题目
      //   index.value = i;

      // 标记/取消标记该题
      tap(i);
      break;
    }
  }
};

// 添加左键点击处理函数
const handleLeftClick = (idx) => {
  index.value = idx;
};

// 添加检查题目是否已答函数
const isAnswered = (idx) => {
  return allAnswers.value[idx]?.filter((a) => a !== "").length > 0;
};

// 添加时间格式化函数
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  const parts = [];
  if (hours > 0) parts.push(`${hours}小时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  parts.push(`${remainingSeconds}秒`);

  return parts.join("");
};

// 处理页面可见性变化
// const handleVisibilityChange = () => {
//   if (document.hidden) {
//     // 记录离开时的时间戳
//     const leaveTime = Date.now();

//     // 显示警告
//     isWarningShown.value = true;
//     ElMessage.warning({
//       message: "警告！检测到您已离开考试页面，3秒后将自动交卷！",
//       duration: 3000,
//       showClose: true,
//       onClose: () => {
//         isWarningShown.value = false;
//       },
//     });

//     // 使用时间戳检查而不是setTimeout
//     warningTimer.value = setInterval(() => {
//       const currentTime = Date.now();
//       const timeAway = currentTime - leaveTime;

//       if (timeAway >= 3000 && isWarningShown.value) {
//         clearInterval(warningTimer.value);
//         ElMessage.error("您已离开考试页面超过3秒，系统将自动交卷！");
//         submitExam(false);
//       }
//     }, 100); // 每100ms检查一次
//   } else {
//     // 用户返回页面
//     if (isWarningShown.value) {
//       isWarningShown.value = false;
//       if (warningTimer.value) {
//         clearInterval(warningTimer.value);
//       }
//       ElMessage.success("您已返回考试页面，可以继续答题");
//     }
//   }
// };

// Add navigation guard
// onBeforeRouteLeave(async (to, from, next) => {
//   // 如果是通过提交触发的路由跳转，直接允许
//   if (canRoute.value) {
//     next();
//     return;
//   }

//   // For self tests
//   if (route.query.type === "selfTest") {
//     try {
//       const result = await ElMessageBox.confirm(
//         "离开页面将删除此次测试，是否确认离开？",
//         "提示",
//         {
//           confirmButtonText: "确认",
//           cancelButtonText: "取消",
//           type: "warning",
//         }
//       );

//       if (result === "confirm") {
//         // Delete the self test
//         await selfTestApi.deleteById(questionItemId);
//         next();
//       } else {
//         next(false);
//       }
//     } catch {
//       // User clicked cancel
//       next(false);
//     }
//   }
//   // For non-self tests
//   else {
//     try {
//       const result = await ElMessageBox.confirm(
//         "离开页面将自动交卷，是否确认离开？",
//         "提示",
//         {
//           confirmButtonText: "确认",
//           cancelButtonText: "取消",
//           type: "warning",
//         }
//       );

//       if (result === "confirm") {
//         submitTitle();
//         next();
//       } else {
//         next(false);
//       }
//     } catch {
//       // User clicked cancel
//       next(false);
//     }
//   }
// });
</script>

<style scoped>
.selfTest_container {
  display: flex;
  margin-top: 10px;
  margin-left: -10px;
  padding-right: 10px;
}

.left {
  width: 300px;
  padding: 10px;
  background-color: white;
  height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
  border: solid 1px rgb(226, 226, 226);
  border-radius: 3px;
}

.left::-webkit-scrollbar {
  width: 6px;
}

.left::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.left::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

.center {
  margin-left: 1%;
  width: 69%;
  height: 70vh;
  padding: 10px;
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border: solid 1px rgb(226, 226, 226);
  border-radius: 3px;
}

.right {
  margin-left: 1%;
  width: 14%;
  height: 70vh;
  padding: 10px;
  background-color: white;
  border: solid 1px rgb(226, 226, 226);
  border-radius: 3px;
}

.squares-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 10px;
}

.square_item {
  background-color: rgb(245, 245, 245);
  border: 1px solid rgb(232, 221, 221);
  border-radius: 2px;
  width: 35px;
  height: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.head_item {
  margin-top: 10px;
  overflow: auto;
  margin-bottom: 20px;
}

.context_item {
  height: 450px;
  overflow: auto;
}

.func_item {
  display: flex;
  justify-content: space-between;
}

.radio-group,
.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: flex-start;
  padding-left: 10px;
}

.radio-item,
.checkbox-item {
  height: 30px;
  line-height: 30px;
}

/* 添加标记题目的样式 */
.square_item.marked {
  background-color: #e6a23c !important;
  color: white;
  border-color: #e6a23c;
}

/* 添加已答题目的样式 */
.square_item.answered {
  background-color: #409eff !important;
  color: white;
  border-color: #409eff;
}

/* 确保标记的样式优先级更高 */
.square_item.marked {
  background-color: #e6a23c !important;
  color: white;
  border-color: #e6a23c;
  z-index: 1;
}

/* 禁用文本选择 */
.selfTest_container {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.subject-text {
  white-space: pre-line; /* 使 \n 换行符生效 */
  margin-top: 10px;
  display: flex;
  margin-left: 5%;
}

/* 或者使用这种样式让文本自动换行 */
.right {
  word-break: break-all;
  white-space: pre-line;
}

.time-text {
  color: #f56c6c; /* Element Plus 的红色 */
  font-size: 18px;
}

/* 添加当前选中题目的样式 */
.square_item.active {
  background-color: #67c23a !important;
  color: white;
  border-color: #67c23a;
  font-weight: bold;
}

/* 确保当前选中题目的样式优先级最高 */
.square_item.active.marked {
  background-color: #67c23a !important;
  color: white;
  border-color: #67c23a;
  font-weight: bold;
}
</style>
